package com.zjw.common.exception.handler;


import com.zjw.common.exception.CommonBizException;
import com.zjw.common.exception.response.ResponseEnum;
import com.zjw.common.exception.response.ResponseUtil;
import com.zjw.common.exception.response.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletResponse;

/**
 * Created with IDEA
 *
 * @description: 全局异常处理类
 * @author: xubo
 * @create: 2018-12-19 16:09
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //在返回自定义相应类的情况下必须有，这是@ControllerAdvice注解的规定

    /**
     * 全局异常
     *
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler
    public ResponseVO<?> exceptionHandler(Exception e, HttpServletResponse response) {
        log.error("全局异常处理, error = {}", e.getMessage());
        return ResponseUtil.error();
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class})
    public ResponseVO<?> methodNotFound(Exception e, HttpServletResponse response) {
        log.error("请求资源未找到", e);
        return ResponseUtil.match(ResponseEnum.NOT_FOUND_RESOURCE);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseVO<?> missParameterException(
            MissingServletRequestParameterException e) {
        log.error("缺少参数：", e);
        return ResponseUtil.match(ResponseEnum.MISS_PARAMS);
    }



    @ExceptionHandler({HttpMessageNotReadableException.class,
            MethodArgumentTypeMismatchException.class, MethodArgumentNotValidException.class})
    public ResponseVO<?> paramInvalidException(Exception e) {
        log.error("参数错误：", e);
        return ResponseUtil.match(ResponseEnum.PARAMS_ERROR);
    }





    @ExceptionHandler({CommonBizException.class})
    public ResponseVO<?> commonBizException(CommonBizException e) {
        log.info("CommonBizException error={}", e.getMessage());
        return ResponseUtil.response(e.getCode(), e.getMessage());
    }
}
